﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace TEAA
{
    public class Selection : RelationalOperation
    {

        private IDictionary<string, string> attributes;
        private IDictionary<string, List<Condition>> selectionConditions;
        private List<Condition> generalConditions;

        public Selection(IDictionary<string, string> attributes, IDictionary<string, List<Condition>> selectionConditions, List<Condition> generalConditions)
        {
            this.attributes = attributes;
            this.selectionConditions = selectionConditions;
            this.generalConditions = generalConditions;
        }

        public DataSet Execute(DataSet data)
        {
            DataSet selection = data.Copy();

            foreach (string attributeName in attributes.Keys)
            {
                List<DataRow> toRemove = new List<DataRow>();

                string tableName = attributes[attributeName];
                DataRowCollection dataRows = null;
                if (selection.Tables.Contains(tableName))
                {
                    dataRows = selection.Tables[tableName].Rows;
                }
                else
                {
                    foreach (DataTable table in selection.Tables)
                    {
                        if (table.Columns.Contains(attributeName))
                        {
                            dataRows = table.Rows;
                            break;
                        }
                    }
                }

                foreach (DataRow row in dataRows)
                {
                    if (!CheckConditions(attributeName, row))
                        toRemove.Add(row);
                }

                foreach (DataRow dr in toRemove)
                    dataRows.Remove(dr);

            }

            return selection;
        }

        private bool CheckConditions(string attributeName, DataRow dataRow)
        {
            foreach (Condition condition in selectionConditions[attributeName])
            {
                if (!condition.IsSatisfiedByCondition(dataRow))
                    return false;
            }

            foreach (Condition condition in generalConditions)
            {
                if (!condition.IsSatisfiedByCondition(dataRow))
                    return false;
            }

            return true;
            
        }
    }
}
